package com.example.index.web;

import com.example.index.web.feign.IUserAction;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;

@RestController
public class IndexAction {
    @RequestMapping("index")
    public String index(HttpServletRequest request){
        return "index : "+ request.getServerPort();
    }
    @Resource
    RestTemplate restTemplate;
    @RequestMapping("user")
    public String user(){
        String ret = restTemplate.getForObject("http://user/user", String.class);
        return "远程访问user:"+ret;
    }

    @Resource
    IUserAction userAction;
    @RequestMapping("userByFeign")
    public String user1(){
        return userAction.user();
    }
    @RequestMapping("hello")
    public String hello(String name){
        return userAction.hello(name);
    }
    @RequestMapping("add")
    public int add(int a ,int b){
        return userAction.add(a,b);
    }
    @RequestMapping("reg")
    public User reg(){
        User user =new User("zhangsan",18, (Data) new Date(),
                new String[]{"唱歌","跳舞","看书"});
        return userAction.reg(user);
    }


    @RequestMapping("headers")
    public void headers(HttpServletRequest request, HttpServletResponse response, PrintWriter out){
        //将请求头的参数输出到页面
        response.setContentType("text/html;charset=utf-8");
        out.println("<ul>");
        final Enumeration<String> headerNames =request.getHeaderNames();
        while (headerNames.hasMoreElements()){
            final String name = headerNames.nextElement();
            out.println("<li>");
            out.println(name+":"+request.getHeader(name));
            out.println("</li>");
        }
        out.println("</ul");

        Cookie cookie =new Cookie("name","zhangsan");
        cookie.setMaxAge(99999);
        response.addCookie(cookie);
    }
}
